import ShooterPlant from "../component/plant/ShooterPlant.js";
import {ANIMS_PATH, Background} from "../common/path.js";
import {Zombie} from "../component/zombie/Zombie.js";
import {Domain} from "../component/Domain.js";
import SunFlower from "../component/plant/SunFlower.js";
import {PlantValueMap} from "../common/config.js";
import SnowPea from "../component/plant/SnowPea.js";

const cards = [
    'card_sunflower',
    'card_peashooter',
    'card_snowpea',
    'card_wallnut',
    'card_cherrybomb',
    'card_threepeashooter',
    'card_repeaterpea',
    //'card_chomper',
    // 'card_puffshroom',
    // 'card_potatomine',
    // 'card_squash',
    // 'card_spikeweed',
    // 'card_jalapeno',
    // 'card_scaredyshroom',
    // 'card_sunshroom',
    // 'card_iceshroom',
    // 'card_hypnoshroom',
    // 'card_redwallnut'
];

export default class LevelScene extends Phaser.Scene {
    constructor() {
        super({key: 'LevelScene'});
        this.level_type = 0
        this.cur_card = ""
        this.curTime = Date.now();
        this.sun_value = 50; // 初始化分数
        // 僵尸创建数据
        this.zombieList = [
            { "time": 1, "map_y": 0, "name": "NormalZombie" },
            { "time": 5, "map_y": 2, "name": "NewspaperZombie" },
            { "time": 20, "map_y": 4, "name": "ConeheadZombie" },
            { "time": 40, "map_y": 3, "name": "ConeheadZombie" },
            { "time": 40, "map_y": 1, "name": "FlagZombie" },
            { "time": 40, "map_y": 2, "name": "ConeheadZombie" },
            { "time": 40, "map_y": 0, "name": "FlagZombie" },
            { "time": 80, "map_y": 1, "name": "ConeheadZombie" },
            { "time": 80, "map_y": 2, "name": "NormalZombie" },
            { "time": 80, "map_y": 3, "name": "ConeheadZombie" },
            { "time": 80, "map_y": 0, "name": "NormalZombie" },
            { "time": 80, "map_y": 4, "name": "FlagZombie" },
            { "time": 80, "map_y": 1, "name": "ConeheadZombie" },
            { "time": 80, "map_y": 1, "name": "ConeheadZombie" }
        ];
    }

    preload() {

        cards.forEach((card, index) => {
            this.load.image(card, `src/resources/graphics/Cards/${card}.png`);
        });


        this.loadImages(ANIMS_PATH)
        this.loadImage(Background, 'jpg')

        // 加载资源
        this.load.image('ChooserBackground', 'src/resources/graphics/Screen/ChooserBackground.png');
        this.load.image('sunflower', 'src/resources/graphics/Cards/card_sunflower.png');
        // this.load.image('PEANORMAL0', 'src/resources/graphics/Bullets/PeaNormal/PeaNormal_0.png');
    }

    loadImage = (item, suffix = 'png') => {
        const name = item.name;
        const count = item.count;
        const path = item.path;

        for (let i = 0; i < count; i++) {
            console.log(`${path}_${i}.png`); // 例如： CherryBomb0, CherryBomb1...
            this.load.image(`${name}${i}`, `${path}_${i}.${suffix}`);
        }
    };

    loadImages(images) {
        for (const category in images) {
            const items = images[category];

            for (const itemKey in items) {
                const item = items[itemKey];

                // 检查是否是一个对象
                if (typeof item === 'object') {
                    if ('name' in item) {
                        // 如果有 name 属性，直接加载该元素的图像
                        this.loadImage(item);
                    } else {
                        // 如果没有 name 属性，继续遍历子元素
                        for (const subItemKey in item) {
                            const subItem = item[subItemKey];

                            // 检查子元素是否是对象并且有 name 属性
                            if (typeof subItem === 'object' && 'name' in subItem) {
                                this.loadImage(subItem);
                            }
                        }
                    }
                }
            }
        }
    };

    create() {
        // this.physics.world.enable(this); // 启用物理引擎
        // 添加背景
        this.add.image(-210, 0, `${Background.name}${this.level_type}`).setOrigin(0, 0);
        this.add.image(20, 0, 'ChooserBackground').setOrigin(0, 0);


        // 创建图像并添加点击事件
        const xOffset = 63; // 图像之间的水平间距
        cards.forEach((card, index) => {
            const image = this.add.image(125 + index * xOffset, 40, card).setInteractive();
            image.setScale(0.7);
            // 为每个图像添加点击事件
            image.on('pointerdown', () => {
                this.onCardClick(card); // 调用点击处理方法
            });
        });


        this.cameras.main.setBackgroundColor('#ffffff');
        // 获取摄像头
        const camera = this.cameras.main;
        // 设置摄像头的边界
        camera.setBounds(0, 0, 1200, 700); // 设置场景的边界（宽度, 高度）

        // 设置摄像头只显示场景的一部分
        camera.setViewport(0, 0, 800, 700); // 设置视口的大小（x, y, 宽度, 高度）

        // 可以通过设置 scroll 来移动摄像头
        camera.scrollX = -400; // 向右移动摄像头
        camera.scrollY = 0; // 向下移动摄像头
        // this.tweens.add({
        //     targets: camera,
        //     scrollX: 400, // 向右移动的目标位置
        //     duration: 5000, // 移动时间（毫秒）
        //     ease: 'Linear', // 动画缓动函数
        //     yoyo: true, // 向右移动完成后反向返回
        //     repeat: 0 // 不重复
        // });
        // 设置输入事件
        this.cursors = this.input.keyboard.createCursorKeys();
        // 监听鼠标按键事件
        this.input.on('pointerdown', (pointer) => {
            // 取消之前的事件
            // pointer.stopPropagation(); // 阻止事件传播
            // pointer.event.preventDefault(); // 阻止默认行为
            if (pointer.rightButtonDown()) {
                this.input.setDefaultCursor(''); // 或者使用 'auto'
            }
            return false
        });
        //  new Plant(this, 210, 300,1);

        for (let i = 0; i < 9; i++) {
            // 每个 RectangleSprite 的 x 坐标间隔 80 像素
            const x = 60 + i * 80; // 60 是起始 x 坐标，80 是间隔
            for (let j = 0; j < 5; j++) {
                const y = 90 + j * 100;
                new Domain(this, x, y, 75, 90, 0x00000000, (dx, dy) => {
                    this.createPlant(this.cur_card,dx,dy)

                    this.cur_card = null;
                    this.input.setDefaultCursor('auto');
                });
            }

        }
        // 创建分数背景
        this.sunValueBackground = this.add.graphics();
        this.sunValueBackground.fillStyle(0xffff00, 1); // 设置背景颜色为黄色
        this.sunValueBackground.fillRect(30, 60, 50, 24); // 绘制矩形背景 (x, y, width, height)

        // 创建分数标签并放置在左上角
        this.sunValueLabel = this.add.text(35, 65, `${this.sun_value}`, {
            fontSize: '12px',
            fill: '#000000' // 设置文字颜色为黑色
        });
        // 开始创建僵尸
        this.createZombies();
       // new Zombie(this, 700, 300, -0.5, "ConeheadZombie");
    }
// 点击事件的回调函数
    onCardClick(card) {
        const plantName=card.split("_")[1].toUpperCase()
        if(this.sun_value>=PlantValueMap[plantName]["pace"] ){
            console.log(`${card} clicked!`);
            this.cur_card = plantName;
            this.input.setDefaultCursor(`url(src/resources/graphics/Cards/${card.split("_")[1].toLowerCase()}_0.png), pointer`);
            // 在这里添加其他逻辑，例如播放动画、更新状态等
        }
    }
    updateScore(amount) {
        this.sun_value += amount;
        this.sunValueLabel.setText(`${this.sun_value}`); // 更新分数标签的文本

    }
    createZombies() {
        this.zombieList.forEach(zombieData => {
            this.time.addEvent({
                delay: zombieData.time*1000, // 延迟时间
                callback: () => {
                    this.spawnZombie(zombieData.map_y, zombieData.name);
                },
                callbackScope: this
            });
        });
    }
    createPlant(plantName, dx, dy) {
        const plantValue =PlantValueMap[plantName];
        const pace = PlantValueMap[plantName]["pace"]
        this.updateScore(pace*-1)
        if(plantValue.type==="SHOOTER"){
            new ShooterPlant(this, dx, dy, 1,plantValue);
        }else {
            new SunFlower(this, dx, dy, 1,plantValue);
        }
    }
    spawnZombie(mapY, name) {
        console.log(`创建僵尸：${name}`)
        // 根据 mapY 计算 x 坐标
        const x = 800; // 右侧边界，您可以根据场景宽度调整
        const y = 90 + mapY * 100; // 每个 y 坐标间隔 100

        // 创建僵尸
        new Zombie(this, x, y, -0.4, name); // 假设 Zombie 的构造函数需要场景、x、y、速度和名称
    }
    update() {
        this.curTime =Date.now(); // 获取当前时间戳（毫秒）
    }
}